package com.cctc.rds.scheduler.server.raft.helper;

import com.cctc.rds.nrpc.core.util.JsonUtils;
import com.cctc.rds.raft.core.RaftCluster;
import com.cctc.rds.raft.core.node.Node;
import com.cctc.rds.raft.core.node.NodeRole;

import java.util.Set;

/**
 * Raft 集群辅助类。
 */
public class RaftHelper {

    public static void checkLeader() {
        NodeRole role = RaftCluster.getNode(RaftCluster.getConfig().getNodeId()).getRole();
        if (role != NodeRole.Leader) {
            Set<Node> nodes = RaftCluster.getAllNodes();
            for (Node node : nodes) {
                if (node.getRole() == NodeRole.Leader) {
                    throw new RuntimeException(JsonUtils.toJson(node.getIpPort()));
                }
            }
            throw new RuntimeException("Raft 集群还未选举出 Leader 节点！！！");
        }
    }

}
